//
//  DMFirebaseManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/8/25.
//

#import "DMFirebaseManager.h"
#import "IMLogUtils.h"
#import "IMFCMService.h"
#import "IMFCMPushService.h"
#import <Firebase/Firebase.h>
#import <FirebaseMessaging/FirebaseMessaging.h>
#import <FirebaseAnalytics/FirebaseAnalytics.h>

@interface DMFirebaseManager()

@property (nonatomic, strong) IMFCMService *fcmService;
@property (nonatomic, strong) IMFCMPushService *fcmPushService;

@end

@implementation DMFirebaseManager

static DMFirebaseManager *_FirebaseManager = nil;

+ (instancetype)shareFirebaseManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _FirebaseManager = [[self alloc] init];
    });
    return _FirebaseManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _fcmService = [IMFCMService sharedService];
        _fcmPushService = [IMFCMPushService sharedService];
    }
    return self;
}

- (void)initializeFirebaseIfNeeded {
    if (![self googlePlist]) return;

    if ([FIRApp defaultApp] == nil) {
        [FIRApp configure];
        [IMLogUtils info:IMLogTagFirebase format:@"Firebase initialized successfully"];
        
        // 初始化Firebase Messaging
        [IMLogUtils info:IMLogTagFirebase format:@"Initializing Firebase Messaging"];
        
        
        
    } else {
        [IMLogUtils info:IMLogTagFirebase format:@"Firebase already initialized"];
    }
}

- (BOOL)googlePlist {
    //获取文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:@"GoogleService-Info.plist" ofType:@""];
    if(path==NULL) {
        [IMLogUtils error:IMLogTagFirebase format:@"GoogleService-Info.plist not found, Firebase will not be initialized"];
        return NO;
    }
    [IMLogUtils info:IMLogTagFirebase format:@"GoogleService-Info.plist found"];
     return YES;
}

#pragma mark - FCM Token Upload

- (IMNetworkTask *)uploadFCMTokenWithAppId:(NSString *)appId
                                      uuid:(NSString *)uuid
                                  fcmToken:(NSString *)fcmToken
                                   success:(IMFCMSuccessBlock _Nullable)success
                                   failure:(IMFCMFailureBlock _Nullable)failure {
    return [self.fcmService uploadFCMTokenWithAppId:appId uuid:uuid fcmToken:fcmToken success:success failure:failure];
}

- (IMNetworkTask *)uploadFCMTokenWithRequest:(IMFCMRequest *)request
                                     success:(IMFCMSuccessBlock _Nullable)success
                                     failure:(IMFCMFailureBlock _Nullable)failure {
    return [self.fcmService uploadFCMTokenWithRequest:request success:success failure:failure];
}

#pragma mark - FCM Push Service

- (BOOL)isFCMInitialized {
    return [self.fcmPushService isFCMInitialized];
}

- (void)initializeFirebaseMessagingWithCompletion:(nullable IMFCMPushCompletionBlock)completion {
    [self.fcmPushService initializeFirebaseMessagingWithCompletion:completion];
}

- (void)initializeFirebaseMessagingWithTargetViewController:(Class)targetViewControllerClass 
                                                 completion:(nullable IMFCMPushCompletionBlock)completion {
    [self.fcmPushService initializeFirebaseMessagingWithTargetViewController:targetViewControllerClass completion:completion];
}

- (void)initializeFirebaseMessagingWithConfig:(IMFCMPushConfig *)config 
                                   completion:(nullable IMFCMPushCompletionBlock)completion {
    [self.fcmPushService initializeFirebaseMessagingWithConfig:config completion:completion];
}

- (nullable NSString *)getCurrentFCMToken {
    return [self.fcmPushService getCurrentFCMToken];
}

- (void)getFCMTokenWithCompletion:(IMFCMPushCompletionBlock)completion {
    [self.fcmPushService getFCMTokenWithCompletion:completion];
}

- (void)requestNotificationPermissionWithCompletion:(void(^)(BOOL granted, NSError * _Nullable error))completion {
    [self.fcmPushService requestNotificationPermissionWithCompletion:completion];
}

- (void)checkNotificationPermissionWithCompletion:(void(^)(UNAuthorizationStatus status))completion {
    [self.fcmPushService checkNotificationPermissionWithCompletion:completion];
}

- (void)setNotificationReceivedCallback:(nullable IMFCMNotificationReceivedBlock)callback {
    [self.fcmPushService setNotificationReceivedCallback:callback];
}

- (void)setTokenRefreshCallback:(nullable IMFCMTokenRefreshBlock)callback {
    [self.fcmPushService setTokenRefreshCallback:callback];
}

- (void)handleNotificationTap:(NSDictionary *)userInfo {
    [self.fcmPushService handleNotificationTap:userInfo];
}

- (void)handleNotificationTap:(NSDictionary *)userInfo viewController:(UIViewController *)viewController {
    [self.fcmPushService handleNotificationTap:userInfo viewController:viewController];
}

- (void)subscribeToTopic:(NSString *)topic completion:(nullable void(^)(NSError * _Nullable error))completion {
    [self.fcmPushService subscribeToTopic:topic completion:completion];
}

- (void)unsubscribeFromTopic:(NSString *)topic completion:(nullable void(^)(NSError * _Nullable error))completion {
    [self.fcmPushService unsubscribeFromTopic:topic completion:completion];
}

- (void)setUserProperty:(NSString *)value forKey:(NSString *)key {
    [self.fcmPushService setUserProperty:value forKey:key];
}

- (void)setAutoInitEnabled:(BOOL)enabled {
    [self.fcmPushService setAutoInitEnabled:enabled];
}

- (BOOL)isFCMNotification:(NSDictionary *)userInfo {
    return [self.fcmPushService isFCMNotification:userInfo];
}

#pragma mark - Firebase Analytics

- (void)logEvent:(NSString *)eventName parameters:(nullable NSDictionary<NSString *, id> *)parameters {
    // 参数校验
    if (!eventName || eventName.length == 0) {
        [IMLogUtils error:IMLogTagFirebase format:@"Firebase Analytics logEvent failed: eventName is empty"];
        return;
    }
    
    // 检查Firebase是否已初始化
    if ([FIRApp defaultApp] == nil) {
        [IMLogUtils error:IMLogTagFirebase format:@"Firebase Analytics logEvent failed: Firebase not initialized"];
        return;
    }
    
    [IMLogUtils info:IMLogTagFirebase format:@"Firebase Analytics logging event: %@ with parameters: %@", eventName, parameters];
    
    // 记录Firebase Analytics事件
    [FIRAnalytics logEventWithName:eventName parameters:parameters];
}

- (void)logEvent:(NSString *)eventName 
      parameters:(nullable NSDictionary<NSString *, id> *)parameters 
      completion:(nullable void(^)(NSError * _Nullable error))completion {
    
    // 参数校验
    if (!eventName || eventName.length == 0) {
        NSError *error = [NSError errorWithDomain:@"DMFirebaseManager" 
                                             code:-1 
                                         userInfo:@{NSLocalizedDescriptionKey: @"Event name is empty"}];
        [IMLogUtils error:IMLogTagFirebase format:@"Firebase Analytics logEvent failed: eventName is empty"];
        if (completion) {
            completion(error);
        }
        return;
    }
    
    // 检查Firebase是否已初始化
    if ([FIRApp defaultApp] == nil) {
        NSError *error = [NSError errorWithDomain:@"DMFirebaseManager" 
                                             code:-2 
                                         userInfo:@{NSLocalizedDescriptionKey: @"Firebase not initialized"}];
        [IMLogUtils error:IMLogTagFirebase format:@"Firebase Analytics logEvent failed: Firebase not initialized"];
        if (completion) {
            completion(error);
        }
        return;
    }
    
    [IMLogUtils info:IMLogTagFirebase format:@"Firebase Analytics logging event: %@ with parameters: %@", eventName, parameters];
    
    // 记录Firebase Analytics事件
    [FIRAnalytics logEventWithName:eventName parameters:parameters];
    
    // Firebase Analytics的logEvent方法是异步的，但没有提供完成回调
    // 这里我们在主队列异步调用completion，表示事件已提交
    if (completion) {
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(nil);
        });
    }
}

- (void)setUserProperty:(NSString *)value forName:(NSString *)name {
    // 参数校验
    if (!name || name.length == 0) {
        [IMLogUtils error:IMLogTagFirebase format:@"Firebase Analytics setUserProperty failed: name is empty"];
        return;
    }
    
    // 检查Firebase是否已初始化
    if ([FIRApp defaultApp] == nil) {
        [IMLogUtils error:IMLogTagFirebase format:@"Firebase Analytics setUserProperty failed: Firebase not initialized"];
        return;
    }
    
    [IMLogUtils info:IMLogTagFirebase format:@"Firebase Analytics setting user property: %@ = %@", name, value];
    
    // 设置用户属性
    [FIRAnalytics setUserPropertyString:value forName:name];
}

- (void)setUserId:(NSString *)userId {
    // 检查Firebase是否已初始化
    if ([FIRApp defaultApp] == nil) {
        [IMLogUtils error:IMLogTagFirebase format:@"Firebase Analytics setUserId failed: Firebase not initialized"];
        return;
    }
    
    [IMLogUtils info:IMLogTagFirebase format:@"Firebase Analytics setting user ID: %@", userId];
    
    // 设置用户ID
    [FIRAnalytics setUserID:userId];
}

@end
